package com.kb5173.search.index.dao.impl;

import com.kb5173.framework.dataaccess.redis.AbstractRedisDAO;
import com.kb5173.framework.shared.entity.BaseEntity;
import com.kb5173.search.common.define.enums.ResponseCodes;
import com.kb5173.search.common.exception.IndexException;
import com.kb5173.search.common.utils.RedisKeyHelper;
import com.kb5173.search.index.dao.IExpireIndexIdRedisDAO;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;

/**
 * @author Chengfei.Sun
 */
@Repository
public class ExpireIndexIdRedisDAOImpl extends AbstractRedisDAO<BaseEntity> implements IExpireIndexIdRedisDAO {
    @Autowired
    @Qualifier("redisTemplate")
    @Override
    public void setTemplate(StringRedisTemplate template) {
        super.template = template;
    };

    @Override
    public void addExpireId(String indexId, Date expireDate) {
        if(StringUtils.isEmpty(indexId)){
            throw new IndexException(ResponseCodes.EmptyIndexId.getCode());
        }
        if(expireDate == null){
            throw new IndexException(ResponseCodes.EmptyExpireDate.getCode());
        }

        zSetOps.add(RedisKeyHelper.expireIndexId(), indexId, expireDate.getTime());
    }

    @Override
    public List<String> getExpireId() {
        Date now = new Date();
        Set<String> result = zSetOps.rangeByScore(RedisKeyHelper.expireIndexId(), 0, now.getTime());
        if(result == null || result.size() == 0){
            return null;
        }
        return new ArrayList<String>(result);
    }

    @Override
    public void deleteExpireId(List<String> indexIds) {
        if (indexIds == null || indexIds.size() == 0) {
            throw new IndexException(ResponseCodes.EmptyIndexId.getCode());
        }
        for (String id : indexIds) {
            zSetOps.remove(RedisKeyHelper.expireIndexId(), id);
        }
    }

}
